import { fileURLToPath, URL } from 'node:url'
import { defineConfig, UserConfig } from 'vite'
import { type ConfigEnv, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import ReactivityTransform from '@vue-macros/reactivity-transform/vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { TDesignResolver } from 'unplugin-vue-components/resolvers'

import { resolve, join } from 'path'
import { glob } from 'glob'
import viteCompression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'
import { dayjs } from 'element-plus'
import type { OutputOptions } from 'rollup'
import { writeFileSync, readFileSync } from 'fs'

console.debug(`fileURLToPath(new URL('./src', import.meta.url))`, fileURLToPath(new URL('./src', import.meta.url)))

const assetsPath = (path: string) => {
  return join('static', path)
}

// 读取package.json获取版本号
const packageJson = JSON.parse(readFileSync(join(process.cwd(), 'package.json'), 'utf-8'))
const appVersion = packageJson.version

// 创建更新clientInfo.json的插件
const updateClientInfoPlugin = (parmas?: { buildTime?: string }) => {
  return {
    name: 'update-client-info',
    apply: 'build' as const,
    buildStart() {
      const buildTime = parmas?.buildTime ?? dayjs().format('YYYY-MM-DD HH:mm:ss')
      const clientInfo = {
        version: appVersion,
        buildTime: buildTime
      }

      // 更新public目录下的clientInfo.json
      const clientInfoPath = join(process.cwd(), 'public', 'clientInfo.json')
      writeFileSync(clientInfoPath, JSON.stringify(clientInfo, null, 2))

      console.log('✅ Updated clientInfo.json with version:', appVersion, 'and build time:', buildTime)
    }
  }
}

/**
 *
 * @returns
 */
const getRollupOptionsInputEntryPath = () => {
  const pageEntry = {} as { [entryAlias: string]: string }
  glob.sync('./src/pages/**/index.html').forEach((entry: string) => {
    entry = entry.replace(/\\/g, '/')
    const pathArr: string[] = entry.split('/')
    const name: string = pathArr[pathArr.length - 2]
    const namevalue = join(process.cwd(), `/src/pages/${name}/index.html`)
    pageEntry[name] = namevalue
  })
  delete pageEntry.pages
  // main存在,index就多余了
  delete pageEntry.index
  // 该页面和index/html 引用的js是一样的
  pageEntry['main'] = join(process.cwd(), `/src/pages/index.html`)
  console.dir('entry+++++++++++')
  console.dir(pageEntry)
  console.dir('entry----------')
  return pageEntry
}

const pageEntry = getRollupOptionsInputEntryPath()
const prefixPathSet = new Set<string>()
const prefixPathMap = new Map<string, string>()
Object.entries(pageEntry).forEach(([key, value]) => {
  const preferValue = value.replace(/\\/g, '/')
  let prefixPath = preferValue.substring(0, preferValue.lastIndexOf('/'))

  if (prefixPath.endsWith('/pages')) {
    prefixPath += '/index'
  }
  prefixPathSet.add(prefixPath)
  prefixPathMap.set(prefixPath, key)
})
// https://vitejs.dev/config/
// export default defineConfig(
// 记录Vite项目多页面应用模式踩坑 https://www.xjx100.cn/news/171534.html?action=onClick
/** 配置项文档：https://cn.vitejs.dev/config */
export default defineConfig((configEnv: ConfigEnv) => {
  const root = './src/pages'
  console.log(`当前文件夹 is`, process.cwd())

  console.log('当前环境 is', configEnv.mode)
  // console.log('env path ', join(process.cwd(), root))

  const viteEnv = loadEnv(configEnv.mode, join(process.cwd()))
  console.log('环境变量 is')
  console.log(viteEnv)

  const { VITE_PUBLIC_PATH } = viteEnv
  console.log(`VITE_PUBLIC_PATH`, VITE_PUBLIC_PATH)

  /**
   * 是否拆分依赖
   * 1 每个依赖都是一个文件
   * 2 页面一个，依赖放vender, common放common
   * 其他是默认
   */
  const splitVender: number = 2
  if (splitVender === 1) {
    console.log(`splitVender为1,将会拆分依赖`)
  }
  let output = void 0 as undefined | OutputOptions
  if (splitVender === 1) {
    output = {
      // hashCharacters: 'base64',
      entryFileNames: assetsPath('js/[name].[hash:10].js'),
      chunkFileNames: assetsPath('js/[name].[hash].js'),
      assetFileNames: assetsPath('css/[name].[hash].[ext]'),
      compact: true,
      manualChunks: (id: string) => {
        // 不同page相同名字的view可能有问题
        if (id.includes('node_modules')) {
          return id.toString().split('node_modules/')[1].split('/')[0].toString() // 拆分多个vendors
        }
      }
    }
  } else if (splitVender === 2) {
    // 拆分多个vendors
    output = {
      compact: true,
      manualChunks: (id) => {
        if (id.includes('node_modules')) {
          return 'vender'
        } else {
          for (const prefixPath of prefixPathSet) {
            if (id.includes(prefixPath)) {
              // console.log(id + '===>' + (prefixPathMap.get(prefixPath) ?? 'default'))
              return prefixPathMap.get(prefixPath) ?? 'default'
            }
          }

          if (id.startsWith(join(process.cwd(), 'src/common/').replace(/\\/g, '/')) || id.startsWith(join(process.cwd(), 'src/components/').replace(/\\/g, '/')) || id.startsWith(join(process.cwd(), 'src/assets/').replace(/\\/g, '/'))) {
            return 'common'
          }

          // console.log(id + '===>other')
          return 'other'
        }
      }
    }
  }

  const buildTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')

  console.log(`process.env.ENV_VARIABLE`, process.env.npm_package_version)
  const userConfig: UserConfig = {
    // envDir: join(process.cwd(), root),
    appType: 'mpa',
    envDir: join(process.cwd()), // 绝对路径
    envPrefix: 'VITE_',
    root: root,
    base: './',
    publicDir: join(process.cwd(), 'public'),
    plugins: [
      vue(),
      // 可能会导致白屏
      // VitePWA({
      //   mode: configEnv.mode as'development' | 'production',
      //   manifest: {
      //     name: 'pwd应用名称',
      //     short_name: 'pwd测',
      //     description: 'pwd应用功能描述'
      //   },
      //   registerType: 'autoUpdate',
      //   workbox: {
      //     clientsClaim: true,
      //     skipWaiting: true
      //   },
      //   devOptions: {
      //     enabled: true  // 并不会在开发模式下提示你安装
      //   }
      // }),
      // mpaPlugin({
      //   pages: getEntryPages(),
      //   historyApiFallback: {
      //     rewrites: getRewrites()
      //   }
      // }),
      // gzip压缩 生产环境生成 .gz 文件
      viteCompression({
        verbose: true,
        disable: true, // 禁用，由nginx处理
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
      vueJsx(),
      legacy({
        renderLegacyChunks: false,
        modernPolyfills: true,
        targets: ['defaults', 'not IE 11', 'chromeAndroid>=52, iOS>=13.1']
      }),
      vueDevTools(),
      AutoImport({
        resolvers: [
          TDesignResolver({
            library: 'vue-next'
          })
        ],
        imports: ['vue', 'vue-router', 'pinia'], // 自动导入vue和vue-router相关函数(只有组件里哦，ts或js文件里面不行～～～)
        dts: join(process.cwd(), 'src/types/auto-import.d.ts') //生成全局引入的文件
      }),
      Components({
        resolvers: [
          TDesignResolver({
            library: 'vue-next'
          })
        ],
        dts: join(process.cwd(), 'src/types/components.d.d.ts') //生成全局引入的文件
      }),
      ReactivityTransform(),
      updateClientInfoPlugin({
        buildTime
      })
    ],
    define: {
      'process.env': {
        buildVersion: buildTime, // 打包时间
        npm_package_version: process.env.npm_package_version // packagejson中的版本
      },
      'import.meta.env.npm_package_version': JSON.stringify(process.env.ENV_VARIABLE)
    },
    resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },
    server: {
      // host: 'localhost',        // 只能localhost和127.0.0.1访问
      // https: false,
      // host: '0.0.0.0',        //
      /** 设置 host: true 才可以使用 Network 的形式，以 IP 访问项目 */
      host: true, //
      port: 12345, // 端口
      /** 是否自动打开浏览器 */
      open: false,
      /** 跨域设置允许 */
      cors: true,

      strictPort: false, // 若端口已被占用,尝试下移一格端口
      proxy: {
        '/gateway': {
          target: process.env.VITE_API_URL || 'https://pinzhi.xxx.com',
          ws: true,
          changeOrigin: true,
          headers: { origin: 'http://localhost' },
          rewrite: (path: string) => path.replace(/^\/gateway/, '')
        }
      }
    },
    //  /** 混淆器 */
    esbuild: {
      /** 打包时移除 console.log */
      pure: ['console.log'],
      /** 打包时移除 debugger */
      drop: ['debugger'],
      /** 打包时移除所有注释 */
      legalComments: 'none'
    },
    build: {
      modulePreload: false,
      outDir: resolve(process.cwd(), 'build'), // 指定输出路径（相对于 项目根目录)
      sourcemap: false, // 构建后是否生成 source map 文件
      chunkSizeWarningLimit: 2048, // 规定触发警告的 chunk(文件块) 大小2048kb
      assetsDir: 'static', // css js 放到static目录下
      minify: 'esbuild',
      cssCodeSplit: false, // css 是否拆分 css 不拆分，在某些情况下会无法引入css
      // 10k以下转成base64
      assetsInlineLimit: 1024 * 10,
      rollupOptions: {
        // 自定义底层的 Rollup 打包配置
        input: pageEntry,
        // https://cn.rollupjs.org/configuration-options/#output-assetfilenames
        //@ts-ignore
        output: output
        // build.rollupOptions.external
      },
      emptyOutDir: true
    }
  }

  return userConfig
})
